package com.xpgk.mvc.brefund;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.log.Log;
import com.xpgk.annotation.Service;
import com.xpgk.constant.ConstantRender;
import com.xpgk.mvc.base.BaseService;
import com.xpgk.mvc.bentryRegister.Customer;
import com.xpgk.mvc.bentryRegister.CustomerAgreement;
import com.xpgk.mvc.bentryRegister.CustomerProduct;
import com.xpgk.mvc.codeSet.Code;
import com.xpgk.mvc.productOutin.ProductOutin;
import com.xpgk.mvc.productStock.ProductStock;
import com.xpgk.mvc.productStock.ProductStockInfo;
import com.xpgk.tools.ToolRandoms;

@Service(name = BrefundService.serviceName)
public class BrefundService extends BaseService {

	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(BrefundService.class);
	public static final String serviceName = "brefundService";

	/**
	 * 获取顾客可退产品
	 * 
	 * @param customerIds
	 * @param organIds
	 * @return
	 */
	public Map<String, Object> getReturnProduct(String customerIds, String organIds) {
		String msg = ConstantRender.render_success_code;
		Map<String, Object> map = new HashMap<>();
		List<CustomerProduct> cpList = ProductReturn.dao.getCustomerProducts(customerIds, organIds);
		if (cpList != null && cpList.size() > 0) {
			map.put("cpList", cpList);
		} else {
			msg = "该顾客无可退订单";
		}
		map.put("msg", msg);
		return map;
	}

	/**
	 * 保存退款信息
	 * 
	 * @param prList
	 * @param customerIds
	 * @param userIds
	 * @param result
	 * @param other
	 * @param operatorIds
	 * @param organIds
	 * @return
	 */
	public String saveReturn(List<ProductReturn> prList, Customer c, String userIds, String result, String other,
			String operatorIds, String organIds) {
		String msg = ConstantRender.render_success_code;

		if (prList != null && prList.size() > 0) {

			for (ProductReturn pr : prList) {

				String cusproSql = getSqlMy(CustomerProduct.sqlId_selByCusAndPro);
				CustomerProduct cp = CustomerProduct.dao.findFirst(cusproSql, c.getStr(Customer.column_ids),
						pr.getStr(ProductReturn.column_productIds), organIds);
				double f = 0d;
				if(cp.getFloat(CustomerProduct.column_proExperience)!=null){
					f = cp.getFloat(CustomerProduct.column_totalExperience) / cp.getFloat(CustomerProduct.column_proExperience);
				}else{
					f = cp.getInt(CustomerProduct.column_count);
				}
				
				
				double n = Math.floor(f);
				if (pr.getInt(ProductReturn.column_num) > n) {
					log.debug("产品剩余不够退款数量，请重新输入退款数量");
					throw new RuntimeException("产品剩余不够退款数量，请重新输入退款数量!");
				} else {

					// 保存退款记录
					pr.set(ProductReturn.column_organIds, organIds)
							.set(ProductReturn.column_customerIds, c.getStr(Customer.column_ids))
							.set(ProductReturn.column_userIds, userIds)
							.set(ProductReturn.column_operatorIds, operatorIds).set(ProductReturn.column_result, result)
							.set(ProductReturn.column_bz, other).set(ProductReturn.column_time, new Date());
					if (!pr.save()) {
						log.debug("保存退款记录失败");
						throw new RuntimeException("保存退款记录失败!");
					}
					if (!pr.getStr(ProductReturn.column_proType).equals(Code.lc_ids)) {
						// 保存产品出入库
						ProductOutin po = new ProductOutin();
						po.set(ProductOutin.column_ids, ToolRandoms.getUuid(true))
								.set(ProductOutin.column_organIds, organIds)
								.set(ProductOutin.column_productIds, pr.getStr(ProductReturn.column_productIds))
								.set(ProductOutin.column_number, pr.getInt(ProductReturn.column_num))
								.set(ProductOutin.column_typeIds, pr.getStr(ProductReturn.column_proType))
								.set(ProductOutin.column_price, pr.getFloat(ProductReturn.column_price))
								.set(ProductOutin.column_date, new Date()).set(ProductOutin.column_style, "2")
								.set(ProductOutin.column_userIds, operatorIds)
								.set(ProductOutin.column_gxsj, new Date());
						if (!po.save()) {
							log.debug("保存产品出入库失败");
							throw new RuntimeException("保存产品出入库失败!");
						}
						// 更新顾客产品剩余

						if(cp.getFloat(CustomerProduct.column_proExperience)!=null){
							if (cp != null) {
								float ex = cp.getFloat(CustomerProduct.column_totalExperience)
										- cp.getFloat(CustomerProduct.column_proExperience)
												* pr.getInt(ProductReturn.column_num);
								float count = cp.getInt(CustomerProduct.column_count) - pr.getInt(ProductReturn.column_num);
								cp.set(CustomerProduct.column_count, count).set(CustomerProduct.column_totalExperience, ex)
										.set(CustomerProduct.column_updateDate, new Date());
								if (!cp.update()) {
									log.debug("更新顾客产品剩余信息失败");
									throw new RuntimeException("更新顾客产品剩余信息失败!");
								}
							}

						}else{
							if (cp != null) {
								
								float count = cp.getInt(CustomerProduct.column_count) - pr.getInt(ProductReturn.column_num);
								cp.set(CustomerProduct.column_count, count)
										.set(CustomerProduct.column_updateDate, new Date());
								if (!cp.update()) {
									log.debug("更新顾客产品剩余信息失败");
									throw new RuntimeException("更新顾客产品剩余信息失败!");
								}
							}

						}
						
						// 更新产品库存表
						String sptSql = getSqlMy(ProductStock.sqlId_selPSByOidsAndPids);
						ProductStock ps = ProductStock.dao.findFirst(sptSql, organIds,
								pr.getStr(ProductReturn.column_productIds));
						if (ps != null) {
							// 更新
							float num = ps.getFloat(ProductStock.column_num) + pr.getInt(ProductReturn.column_num);
							ps.set(ProductStock.column_num, num).set(ProductStock.column_gxsj, new Date());
							if (!ps.update()) {
								log.debug("更新产品总库存失败");
								throw new RuntimeException("更新产品总库存失败!");
							}

						}
						// 更新库存明细
						SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
						String gxsj = "%" + dateFormater.format(new Date()) + "%";
						String psiSql = getSqlMy(ProductStockInfo.sqlId_selByOidsAndPidsAndTime);
						ProductStockInfo psi = ProductStockInfo.dao.findFirst(psiSql, organIds,
								pr.getStr(ProductReturn.column_productIds), gxsj);
						if (psi != null) {
							// 库存详细信息减少库存
							float num = psi.getFloat(ProductStockInfo.column_stock)
									+ pr.getInt(ProductReturn.column_num);
							psi.set(ProductStockInfo.column_stock, num).set(ProductStockInfo.column_gxsj, new Date());
							if (!psi.update()) {
								log.debug("更新库存明细失败");
								throw new RuntimeException("更新库存明细失败!");
							}

						} else {
							ProductStockInfo psInfo = new ProductStockInfo();
							String psinfoids = ToolRandoms.getUuid(true);
							psInfo.set(ProductStockInfo.column_ids, psinfoids)
									.set(ProductStockInfo.column_organids, organIds)
									.set(ProductStockInfo.column_productID, pr.getStr(ProductReturn.column_productIds))
									.set(ProductStockInfo.column_type, pr.getStr(ProductReturn.column_proType))
									.set(ProductStockInfo.column_stock, ps.getFloat(ProductStock.column_num))
									.set(ProductStockInfo.column_gxsj, new Date());
							if (!psInfo.save()) {
								log.debug("保存产品库存记录失败！！");
								throw new RuntimeException("保存产品库存记录失败!");
							}
						}

					} else {
						// 终止协议
						CustomerAgreement ca = c.getCustomerAgreement();
						if (ca != null) {
							ca.set(CustomerAgreement.column_state, "0").set(CustomerAgreement.column_time, new Date());
							if (!ca.update()) {
								log.debug("终止协议失败！！");
								throw new RuntimeException("终止协议失败!");
							}
						}
					}
				}

			}

		}
		return msg;
	}

}
